package com.appwidge;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class AppWidgetServiceTest extends Service {
	private final static String TAG = "AppWidgetServiceTest";

	// 更新wedget 的广播对应的action
	private final String ACTION_UPDATE_ALL = "com.appwidge.UPDATE_ALL";
	// 周期性更新的time
	private final static int UPDATE_TIME = 5000;
	// 周期性更新 widget 的线程
	private UpdateThread mUpdateThread;
	private Context mContext;
	// 更新周期的计数
	private int count = 0;

	@Override
	public void onCreate() {
		//创建线程并启动
		mUpdateThread = new UpdateThread();
		mUpdateThread.start();
		
		mContext = getApplicationContext();
		super.onCreate();
	}

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.i(TAG, "onStartCommand");
		super.onStartCommand(intent, flags, startId);
		
		return START_STICKY;
	}

	@Override
	public void onDestroy() {
		if(mUpdateThread !=null){
			mUpdateThread.interrupt();
		}
		super.onDestroy();
	}
	
	private class UpdateThread extends Thread{
		@Override
		public void run() {
			super.run();
			try {
				count =0;
				while (true) {
					Log.d(TAG, "run ... count:"+count);
					count ++;
					Intent intent = new Intent(ACTION_UPDATE_ALL);
					mContext.sendBroadcast(intent);
					Thread.sleep(UPDATE_TIME);	
				}	
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}
